//
//  UserAccountViewModel.m
//  kuangjia
//
//  Created by 张帅 on 15/9/29.
//  Copyright © 2015年 ZhangShuai. All rights reserved.
//

#import "UserAccountViewModel.h"
#import "NetworkTools.h"

@interface UserAccountViewModel ()

@end

@implementation UserAccountViewModel

- (instancetype)init

{
    self = [super init];
    if (self) {
      
        self.userAccount =  [UserAccountTool loadUserAccount];
    }
    return self;
}


+ (instancetype)sharedUserAccount{

    static id instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        
    });
    return instance;
    
}

- (NSString*)accessToken{

    return self.userAccount.access_token;
}

-(NSURL*)avatarUrl{
    
    return [NSURL URLWithString:[UserAccountTool loadUserAccount].avatar_large];

}

-(BOOL)userLogon{
    
    return self.accessToken != nil;
}

- (RACSignal *)loadUserAccountCode:(NSString *)code
{
 
    
    return  [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
       
        [[[NetworkTools sharedTools] loadAccessTokenwithCode:code] subscribeNext:^(NSDictionary *dict) {
            
            UserAccount *account =[ UserAccount userAccountWithDict: dict ];
            
            self.userAccount =account;
            
            NSLog(@"account%@",account);
            
            [[[NetworkTools sharedTools] loadUserInfoWithuid:account.uid ] subscribeNext:^(NSDictionary *dict) {
                
                  // 设置帐号的属性
                account.name =  dict[@"name"];
                
                account.avatar_large = dict[@"avatar_large"];
            
                NSLog(@"拿到值的%@",account);
                
                [UserAccountTool saveAccount:account];
                [subscriber sendCompleted];
                
            } error:^(NSError *error) {
                
            }];
            
        } error:^(NSError *error) {
            
            [subscriber sendError:error];
        }];
        
        
        return nil;
    }];
}

@end

